﻿using System;
using System.Web.Script.Serialization;
using Microsoft.Web.WebSockets;

namespace WebSockets.WS
{
    public class WsHandler : WebSocketHandler
    {
        private static readonly WebSocketCollection Clients = new WebSocketCollection();

        public override void OnOpen()
        {
            Clients.Add(this);

            var userId = WebSocketContext.QueryString["userId"];
            Clients.Broadcast(new JavaScriptSerializer().Serialize(new Message
            {
                Data = string.Format("Welcome from {0} userId {1}", WebSocketContext.UserHostAddress, userId),
                At = DateTime.Now.ToLongTimeString(),
            }));
        }

        public override void OnMessage(string message)
        {
            Send(new Message
            {
                Data = string.Format("'{0}' was received from user", message),
                At = DateTime.Now.ToLongTimeString()
            });
        }

        public override void OnClose()
        {
            base.OnClose();
        }

        public override void OnError()
        {
            base.OnError();
        }

        private void Send(Message msg)
        {
            Send(new JavaScriptSerializer().Serialize(msg));
        }
    }

    public class Message
    {
        public string Data { get; set; }

        public string At { get; set; }
    }
}